package main

import (
	"net"
	"os"

	"../pb"
	"github.com/op/go-logging"
	"google.golang.org/grpc"
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	listen_addr = kingpin.Flag("listen_addr", "listen address.").Required().Short('a').String()
	path        = kingpin.Flag("path", "base path.").Required().Short('p').String()
	bufSize     = kingpin.Flag("bufSize", "buffer size.").Required().Short('b').Int64()
	log_file    = kingpin.Flag("log", "log file.").String()
	log         = logging.MustGetLogger("server")
)

func main() {
	kingpin.Parse()
	if *log_file == "" {
		bk := logging.NewLogBackend(os.Stderr, "", 0)
		logging.SetBackend(bk)
	} else {
		file, err := os.OpenFile(*log_file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			log.Errorf("open log file %s , error: ", *log_file, err)
		}
		defer file.Close()
		bk := logging.NewLogBackend(file, "", 0)
		logging.SetBackend(bk)
	}

	lis, err := net.Listen("tcp", *listen_addr)
	if err != nil {
		log.Errorf("failed to listen: %v", err)
	}
	defer lis.Close()

	gs := grpc.NewServer()
	pb.RegisterFileServiceServer(gs, &fileService{bufSize: *bufSize, basePath: *path})
	gs.Serve(lis)
}
